package com.icbc.controller;


import com.icbc.dbconfig.DBContextHolder;
import com.icbc.mapper.UserMapper;
import com.icbc.pojo.User;
import com.icbc.service.DBChangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private DBChangeService dbChangeServiceImpl;
    @Autowired
    UserMapper userService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/test")
    public  String test() throws Exception {

        String result;

        //切换到数据库dbtest2
        String datasourceId="docker_mysql_3311";
        dbChangeServiceImpl.changeDb(datasourceId);
        List<User> userList= userService.queryUserInfo();
        System.out.println(userList.toString());

        //再切换到数据库dbtest3
        dbChangeServiceImpl.changeDb("docker_mysql_3312");
        List<User> userList3= userService.queryUserInfo();
        System.out.println(userList3.toString());

        //切回主数据源
        DBContextHolder.clearDataSource();
        result = "instance1: \n" + userList.toString() + "\ninstance2: \n" + userList3.toString();
        return result;
    }

    /**
     * 在3311实例插入数据
     *
     */
    @GetMapping("/insert")
    public String insert() throws Exception {
        //切换到数据库dbtest2
        String datasourceId="docker_mysql_3311";
        dbChangeServiceImpl.changeDb(datasourceId);
        User user = new User();
        user.setUserName("ICBC");
        user.setAge("36");
        userService.insertUser(user);
        System.out.println(user.toString());

        return "insert finished.";
    }
}
